<?php
/**
 * Created by PhpStorm.
 * User: DSPC
 * Date: 2018/6/21
 * Time: 16:45
 */

namespace App\Utils;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;

class Code
{
    // 执行成功
    const SUCCESS = 200;
    // 未满足执行条件
    const LACK_OF_CONDITIONS = 201;
    // 没有授权
    const NOT_BINDING = 202;
    // 无效数据
    const INVALID_DATA = 204;
    // 数据不全
    const INCOMPLETE_DATA = 205;
    // 无权访问
    const UNAUTHORIZED_ACCESS = 401;
    // 身份过期
    const EXPIRED = 403;
    // 参数有误
    const PARAMETER_ERROR = 406;
    // 重复数据
    const EXIST_REPEAT = 409;
    // 没有数据
    const EMPTY_DATA = 410;
    // 接口异常
    const REMOTE_SERVER = 412;
    // 没绑手机
    const NO_PHONE = 901;
    // 账号过期
    const EXPIRED_ACCOUNT = 902;
    // 库存不足
    const INVENTORY_SHORTAGE = 999;
    // 程序错误
    const EXCEPTION_ERROR = 500;

    /**
     * 数据请求响应
     * @param array $data
     * @param bool $returnParams
     * @param string $dataKey
     * @return array|\Illuminate\Http\JsonResponse
     */
    public static function response($data = [], $returnParams = true, $dataKey = 'data'){
        $response = [
            'code' => self::SUCCESS,
            'message' => '执行成功'
        ];
        if ($returnParams && $data !== true){
            if (!is_array($data) && $dataKey === null) {
                return $data;
            }
            $data = json_decode(json_encode($data), true);
            if (!isset($data['current_page'])){
                $data = [$dataKey => $data];
            }
            $response = array_merge($response, $data);
        }
        return response()->json($response);
    }

    /**
     * 失败请求响应
     * @param $message
     * @param $code
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public static function failure($message, $code){
        return response([
            'code' => $code ? $code : self::EXCEPTION_ERROR,
            'message' => $message
        ])->header('Content-Type', 'application/json; charset=UTF-8');
    }

    /**
     * 抛出异常信息
     * @param \Throwable $e
     * @param null $code
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public static function exception(\Throwable $e, $code = null){
        $code = $code === null ? $e->getCode() : $code;
        if (strlen($code) != 3){
            $code = self::EXCEPTION_ERROR;
        }
        $error = $e->getMessage();
        if (($code == 500 || $code == 412)) {
            // 打印日志
            self::exceptionLog($e);
            if (!config('app.debug', true)){
                $error = '请稍后尝试';
            }
        }
        return self::failure($error, $code);
    }

    /**
     * 记录异常日志
     * @param \Throwable $e
     */
    public static function exceptionLog(\Throwable $e){
        $errLog = '=====================================================================================' .PHP_EOL;
        $errLog .= $e->getMessage() .PHP_EOL;
        if (Route::current()) {
            $errLog .= (new Request())->getMethod().": ". Route::current()->uri .PHP_EOL;
        }
        $errLog .= $e->getFile() . ' -> Line：' . $e->getLine() .PHP_EOL;
        $errLog .= '------------------------------------------------------------------------------------------------------------------------' .PHP_EOL;
        Log::error($errLog);
    }

    /**
     * 打印日志
     * @param $text
     * @param null $code
     */
    public static function log($text, $code = null){
        $log = '=====================================================================================' .PHP_EOL;
        if (Route::current()) {
            $log .= (new Request())->getMethod().": ". Route::current()->uri .PHP_EOL;
        }
        if ($code){
            $log .= "【{$code}】".$text .PHP_EOL;
        } else {
            $log .= $text .PHP_EOL;
        }
        $log .= '------------------------------------------------------------------------------------------------------------------------' .PHP_EOL;
        Log::error($log);
    }
}
